package com.flyxiaozhu.erp.admin.authorize;

import com.flyxiaozhu.erp.core.entities.Permission;
import com.flyxiaozhu.erp.core.repositories.PermissionRepository;
import com.flyxiaozhu.erp.core.utils.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class PermissionManager {
    private PermissionRepository permissionRepository;

    @Autowired
    public void setPermissionRepository(PermissionRepository permissionRepository) {
        this.permissionRepository = permissionRepository;
    }

    private Permission buildDefaultPermission(String identify) {
        Permission permission = new Permission();
        permission.setIdentity(identify);
        permission.setName("未定义权限");

        return permission;
    }

    public void init() {
        PermissionScanner scanner = new PermissionScanner("com.flyxiaozhu.erp.admin.controllers");

        List<Permission> permissions = permissionRepository.findAll();
        Set<String> dbPerms = new HashSet<>(CollectionUtils.map(permissions, Permission::getIdentity));
        Set<String> realPerms = scanner.getPermissions();

        Set<String> newPerms = new HashSet<>(realPerms);
        newPerms.removeAll(dbPerms);

        Set<String> discardPerms = new HashSet<>(dbPerms);
        discardPerms.removeAll(realPerms);

        if (discardPerms.size() > 0) {
            System.out.println("============无用的权限============");
            System.out.println(discardPerms);
        }

        if (newPerms.size() > 0) {
            System.out.println("============新注册权限============");
            System.out.println(newPerms);
        }

        List<Permission> permissiones = new ArrayList<>();
        for (String perm : newPerms) {
            permissiones.add(buildDefaultPermission(perm));
        }
        System.out.println(permissiones);
        permissionRepository.saveAll(permissiones);
    }
}
